package com.smbms.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smbms.entity.User;
import com.smbms.service.UserService;
import com.smbms.tool.Constants;

@Controller
public class LoginController {
	@Resource
	private UserService userService;
	
	//进入登录页面
	@RequestMapping("login")
	public String login(){
		return "login";
	}
	
	//点击登录时进行登录验证
	@RequestMapping(value="dologin",method=RequestMethod.POST)
	//获取从表单里提交过来的数据,为input的name属性
	public String doLogin(String userCode,String userPassword,HttpSession session,Model model){
		User user = userService.login(userCode);
		if(user == null){
			model.addAttribute("error", "用户名不存在");
		}else if(user != null && !user.getUserPassword().equals(userPassword)){
			model.addAttribute("error", "密码输入错误");
		}else{
			session.setAttribute(Constants.USER_SESSION, user);	//登录成功就设置session
			return "redirect:main";	//重定向发送请求
		}
		
		return "login";
	}
	
	//登录成功进入主页面(如果没有登录用户,则不能进入主页面,包括主页面里的其他功能页面,则需要进行自定义拦截)
	@RequestMapping("main")
	public String main(){
		return "frame";
	}
	
	//退出用户
	@RequestMapping("logout")
	public String logout(HttpSession session){
		//清空session
		session.removeAttribute(Constants.USER_SESSION);
		return "login";
	}
}
